<template>
  <div>
    <!-- 面包屑头部导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input clearable @clear="getUsers" v-model="queryData.query" placeholder="请输入内容">
            <el-button @click="getUsers" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button @click="addDialogVisible=true" type="primary">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <!-- 状态列 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- scope.row一行的数据 -->
            <el-switch @change="editSwitch(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="180">
          <template slot-scope="item">
            <!-- 编辑按钮 -->
            <el-button
              @click="showEditUser(item.row.id)"
              size="mini"
              type="primary"
              icon="el-icon-edit"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              @click="delUser(item.row.id)"
              size="mini"
              type="danger"
              icon="el-icon-delete"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                @click="showSetRoleDialog(item.row)"
                size="mini"
                type="warning"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog 
    @close="resetAddForm" 
    title="添加用户" 
    :visible.sync="addDialogVisible" 
    width="50%">
      <!-- 内容主体部分 -->
      <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button @click="addUser" type="primary">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog 
    @close="resetEditForm" 
    title="编辑用户" 
    :visible.sync="editDialogVisible" 
    width="50%">
      <!-- 内容主体部分 -->
      <el-form :model="editForm" 
      :rules="editRules" 
      ref="editForm" 
      label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button @click="editUser" type="primary">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" width="50%">
      <div>
        <p>当前用户:{{userInfo.username}}</p>
        <p>当前的角色:{{userInfo.role_name}}</p>
        <div>
          分配新角色：
          <!-- v-model的值为当前被选中的el-option的 value 属性值 -->
          <el-select v-model="activeOpt" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="setRoleSub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("邮箱格式错误"));
    };

    // 定义手机号码校验规则错误
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("手机号码格式错误"));
    };

    return {
      queryData: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      addForm: {
        username: "test",
        password: "123456",
        email: "2109597105@qq.com",
        mobile: 18755180897
      },
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 7, message: "长度在 2 到 7 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // validator指向校验规则  trigger触发条件
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      editDialogVisible: false,
      editForm: {},
      editRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // validator指向校验规则  trigger触发条件
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      roleDialogVisible: false,
      userInfo: {},
      roleList: [],
      activeOpt: ""
    };
  },

  methods: {
    async getUsers() {
      var res = await this.axios.get("users", {
        params: this.queryData
      });
      //将数据传给
      //   console.log(res);
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    async editSwitch(row) {
      console.log(row);
      var res = await this.axios.put(`users/${row.id}/state/${row.mg_state}`);
      console.log(res);
      if (res.meta.status == 200) {
        this.$mg.success("修改成功");
      } else {
        this.$mg.success("修改失败");
      }
    },
    
    // 每页多少条发生变化时触发
    handleSizeChange(val) {
      console.log(val);
      this.queryData.pagesize = val;
      this.getUsers();
    },
    // 页码发生变化时触发
    handleCurrentChange(val) {
      console.log(val);
      this.queryData.pagenum = val;
      this.getUsers();
    },

    // 重置添加表单
    resetAddForm() {
      this.$refs.addForm.resetFields();
    },
    // 添加表单提交
    addUser() {
      this.$refs.addForm.validate(async flag => {
        if (!flag) return;
        var res = await this.axios.post("users", this.addForm);
        console.log(res);
        if (res.meta.status == 201) {
          this.$mg.success("添加成功");
          this.addDialogVisible = false;
          this.getUsers();
        } else {
          this.$mg.error(res.meta.msg);
        }
      });
    },

    // 根据id获取表单数据
    async showEditUser(id) {
      var res = await this.axios.get("users/" + id);
      console.log(res);
      if (res.meta.status == 200) {
        this.editForm = res.data;
      } else {
        console.log(res.meta.msg);
      }
      this.editDialogVisible = true;
    },
    // 重置编辑表单
    resetEditForm() {
      this.$refs.editForm.resetFields();
    },
    // 编辑用户提交
    editUser() {
      this.$refs.editForm.validate(async flag => {
        if (!flag) return;
        console.log("表单校验合法");
        var res = await this.axios.put("users/" + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        });
        console.log(res);
        if (res.meta.status == 200) {
          this.$mg.success("更新成功");
          this.editDialogVisible = false;
          this.getUsers();
        } else {
          this.$mg.error(res.meta.msg);
        }
      });
    },

    // 删除操作 确认提示
    delUser(id) {
      this.$cfm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          console.log("确认删除");
          var res = await this.axios.delete("users/" + id);
          if (res.meta.status == 200) {
            this.$mg.success("删除成功");
            this.getUsers();
          } else {
            this.$mg.error(res.meta.msg);
          }
        })
        .catch(() => {
          this.$mg.info("已取消删除");
        });
    },

    // 显示分配角色对话框
    async showSetRoleDialog(row) {
      this.userInfo = row;
      this.roleDialogVisible = true;
      var res = await this.axios.get("roles");
      if (res.meta.status == 200) {
        this.roleList = res.data;
      }
    },
    // 提交分配新角色
    async setRoleSub(){
      if(!this.activeOpt) return this.$mg.error('请选择新角色')
      var res=await this.axios.put(`users/${this.userInfo.id}/role`,{
        rid:this.activeOpt
      })
      if(res.meta.status==200){
        this.roleDialogVisible=false;
        this.getUsers();
        this.$mg.success('更新成功')
      }
    }

  },

  created() {
    this.getUsers();
  }
};
</script>

<style lang='less' scoped>
</style>
